<?php

namespace app\load\service;

use app\load\loadModel\AdminModel;
use app\load\loadModel\OaModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 审批记录服务层
 */
class FlowRecordService
{

    /**
     * 获取审核流程节点
     * @param $id
     * @param $type
     * @return array
     */
    public function list($id , $type): array
    {
        return  OaModel::FlowRecord()->list(['f.action_id'=>$id,'f.type'=>$type], 'f.*,a.name,a.thumb');
    }

    /**
     * 获取审核流程节点
     * @param int $id |id
     * @param int $type | 类型
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function get_flow_nodes(int $id = 0, int $type = 1): array
    {

        $flowModel = OaModel::FlowRecord();
        $flowStepModel = OaModel::FlowStep();
        $adminModel = AdminModel::Admin();

        $flows = $flowStepModel
            ->where(['action_id' => $id, 'type' => $type, 'delete_time' => 0])
            ->order('sort asc')
            ->select()
            ->toArray();

        $flowStepIds = array_column($flows, 'id');
        $userIds = $adminModel
            ->field('id, name, thumb')
            ->whereIn('id', function ($query) use ($flowStepIds) {
                $query->name('FlowStep')->where('id', 'in', $flowStepIds)->field('flow_uids');
            })
            ->select()
            ->toArray();

        $userIdsMap = [];
        foreach ($userIds as $user) {
            $userIdsMap[$user['id']] = $user;
            $userIdsMap[$user['id']]['check_time'] = 0;
            $userIdsMap[$user['id']]['content'] = '';
            $userIdsMap[$user['id']]['status'] = 0;
        }

        $checkRecords = $flowModel
            ->whereIn('step_id', $flowStepIds)
            ->order('check_time desc')
            ->select()
            ->toArray();

        foreach ($checkRecords as $record) {
            $userId = $record['check_user_id'];
            if (isset($userIdsMap[$userId])) {
                $user = &$userIdsMap[$userId];
                $user['check_time'] = date('Y-m-d H:i', $record['check_time']);
                $user['content'] = $record['content'];
                $user['status'] = $record['status'];
            }
        }

        $checkList = $flowModel->list(['f.step_id' => $flowStepIds], 'f.*,a.name,a.thumb');

        foreach ($flows as &$flow) {
            $flow['user_id_info'] = array_values($userIdsMap);
            $flow['check_list'] = $checkList;
        }

        return  $flows;
    }

}